<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>分类管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类{{ isAdd }}</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <h1 style="margin-bottom: 15px">分类{{ isAdd }}</h1>
      <el-form
        :model="cateForm"
        ref="cateRef"
        label-width="100px"
        :inline="false"
        size="normal"
      >
        <el-form-item label="父级分类">
          <el-cascader
            style="width: 250px"
            v-model="cateForm.parentId"
            :options="parentList"
            :props="defaultParams"
            :clearable="true"
            :disabled="id?true:false"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="分类名称">
          <el-input v-model="cateForm.name" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">{{ isAdd }}</el-button>
          <el-button @click="$router.push('/cateList')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
  </div>
</template>

<script>
export default {
  props: {
    id: {},
  },
  data() {
    return {
      cateForm: {
        name: "",
        parentId:null
      },
      parentList: [],
      defaultParams: {
        label: "name",
        value: "_id",
        children: "children",
        checkStrictly: true
      },
    };
  },
  methods: {
    //点击表单提交按钮
    async onSubmit() {
      if (this.id) {
        const res = await this.$http.put(`/category/${this.id}`, this.cateForm);

        if (res.data) {
          this.$router.push("/cateList");
          this.$message({
            message: "编辑成功",
            type: "success",
          });
        }
      } else {
        const res = await this.$http.post("/category", this.cateForm);
        if (res.data) {
          this.$router.push("/cateList");
          this.$message({
            message: "添加成功",
            type: "success",
          });
        }
      }
    },

    //获取父级列表
    async getParentList() {
      let res = await this.$http.get("/other/cateParent");
      this.parentList = res.data;
    },
    
    //获取分类信息
    async getCate(){
      let res = await this.$http.get(`/category/${this.id}`)
      this.cateForm = res.data
    }
  },
  created() {
    this.getParentList();
    this.id && this.getCate()
  },
};
</script>

<style lang="less" scoped>
</style>